package com.bjsxt.userscenter.head.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.bjsxt.userscenter.common.controller.BaseController;
import com.bjsxt.userscenter.common.util.ConstatFinalUtil;
import com.bjsxt.userscenter.common.util.EncryptUtil;
import com.bjsxt.userscenter.users.pojo.AUsers;
import com.bjsxt.userscenter.users.pojo.AUsersEnum;
import com.bjsxt.userscenter.users.pojo.AUsersExtend;
import com.bjsxt.userscenter.users.service.IUsersService;
/**
 * 前台（广大网民）
 * @author hou
 *
 */
@Controller
public class NoLoginController extends BaseController
{
	@Resource
	private IUsersService usersService;
	/**
	 * 打开登录页面
	 * @throws IOException 
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		
		ConstatFinalUtil.LOGGER.info("----login-----");		
		HttpSession session = request.getSession();
		//如果session有管理员说明已经登录
		AUsers users = (AUsers) session.getAttribute("users");
		if(users != null)
		{
			//已经登录
			if(this.returnUrl(request,response,users))
			{
				return null;
			}else
			{
				//登陆成功
				return "redirect:/head/users/main.ht,";
			}
		}
		return "/head/login";
		
	}
	
	/**
	 * 登录提交
	 * @throws IOException 
	 */
	@RequestMapping("/loginSubmit")
	public String loginSubmit(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		ConstatFinalUtil.LOGGER.info("----loginSubmit----");
		HttpSession session = request.getSession();
		//接收参数
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String rand = request.getParameter("rand");
		//从session去除验证码图片的验证
		String randSess = session.getAttribute("rand")+"";
		//对比验证码，万能验证码
		if((randSess != null && randSess.equalsIgnoreCase(rand)) || "0715".equalsIgnoreCase(rand))
		{
			//根据邮箱查询管理员
			Map<String, Object>condMap = new HashMap<String,Object>();
			condMap.put("email", email);
			AUsers users = this.usersService.findOneUsersService(condMap);
			//用户存在
			if(users != null)
			{
				//验证密码正确
				if(EncryptUtil.checkPass(password, users.getPassword()))
				{
					//密码正确
					if(users.getStatus() == AUsersEnum.STATUS_ENABLE.getStatus())
					{
						//启用
						//放入session
						session.setAttribute("users", users);
						session.setAttribute("lastLoginTime", users.getLastLoginTime());
						
						//修改管理员信息
						users.setLastLoginTime(new Date());
						/*admins.getCreateTime().toLocaleString():
						 * 2016-11-11 11:11:11
						 * */
						ConstatFinalUtil.LOGGER.info("登陆成功;id:{},邮箱:{},登陆时间:{}",users.getId(),users.getEmail(),
								users.getLastLoginTime().toLocaleString());
						
						if(this.returnUrl(request,response,users))
						{
							return null ; 
						}else
						{
							/* 登陆成功 */
							return "redirect:/head/users/main.htm";
						}
						
					}else
					{
						/* 禁用 
						 * 4:账户已禁用,请联系管理员
						 * */
						this.info = ConstatFinalUtil.INFO_JSON.getString("4") ; 
					}
				}else
				{
					/* 密码不正确 */
					this.info = ConstatFinalUtil.INFO_JSON.getString("5") ; 
				}
				
				/* 保留邮箱 */
				request.setAttribute("email", email);
			}else
			{
				/* 邮箱不存在,用户不存在 */
				this.info = ConstatFinalUtil.INFO_JSON.getString("6") ; 
			}
		}else
		{
			/* 验证码不正确 */
			this.info = ConstatFinalUtil.INFO_JSON.getString("7") ; 
		}
		
		request.setAttribute("info", info);
		
		/*String id = request.getParameter("id");
		if("1".equals(id))
		{
			 登陆成功 
			return "redirect:/back/admins/main.htm";
		}*/
		return this.login(request,response); 
	}
	/**
	 * -----------步骤2----------------
	 * 如果带上reurnUrl:跳转到returnUrl,并且加上token参数,页面跳转
	 * 如果木有带,跳转到用户中心自己登陆后的页面
	 * @param request
	 * @return 如果是true,表示有returnUrl,如果是false,表明木有returnUrl
	 * @throws IOException 
	 */
	private boolean returnUrl(HttpServletRequest request,HttpServletResponse response,AUsers users) throws IOException
	{
		String returnUrl = request.getParameter("returnUrl");
		ConstatFinalUtil.LOGGER.info("returnUrl===={}" , returnUrl);
		/* 不传为null,传了空字符串,两者合二为一 */
		if(returnUrl == null)
		{
			returnUrl = "" ; 
		}
		
		if(!"".equalsIgnoreCase(returnUrl))
		{
			/* 
			 * 生成uuid
			 * 加上token
			 * 	如果原来的url木有参数,加上?
			 * 	如果有参数,加上&
			 * 将returnUrl:加密
			 *  */
			/*生成uuid*/
			String token = UUID.randomUUID() + "" ; 
			
			/* 存储到Token的容器中,值为管理员对应的JSON信息 */
			/*JSONObject adminsJSON = new JSONObject();
			 存储管理员对象可开放的字段 
			adminsJSON.put("id", admins.getId());
			adminsJSON.put("email", admins.getEmail());
			adminsJSON.put("createTime", this.dateFormatUtil.format(admins.getCreateTime()));
			adminsJSON.put("updateTime", this.dateFormatUtil.format(admins.getUpdateTime()));
			adminsJSON.put("lastLoginTime", this.dateFormatUtil.format(admins.getLastLoginTime()));
			ConstatFinalUtil.TOKENS_MAP.put(token, adminsJSON);*/
			
			/* 调用POJO对应的json存储 */
			ConstatFinalUtil.TOKENS_MAP.put(token, users.toJSON());
			
			/*加上token*/
			String tokenIndex = "token=" ;
			if(returnUrl.indexOf("?") != -1 && returnUrl.indexOf(tokenIndex) != -1)
			{
				/* http://aaa.com?token=aaa
				 * http://aaa.com?id=1&a=2&token=2222
				 * http://aaa.com?id=1&a=2&abcdtoken=2222:自行解决
				 *  */
				returnUrl = returnUrl.substring(0, returnUrl.indexOf(tokenIndex));
				returnUrl = returnUrl + "token=" + token ; 
			}else if(returnUrl.indexOf("?") != -1)
			{
				/* http://aaa.com?id=10
				 * 木有token */
				/* 肯定有参数 */
				returnUrl = returnUrl + "&token=" + token ; 
			}else
			{
				/* 肯定木有参数 */
				returnUrl = returnUrl + "?token=" + token ; 
			}
			ConstatFinalUtil.LOGGER.info("returnUrl==加上token=={}",returnUrl);
			/* URL跳转 */
			response.sendRedirect(returnUrl);
			/* 将returnUrl:加密 */
			/*returnUrl = URLEncoder.encode(returnUrl, "UTF-8");*/
			return true ; 
		}
		return false ; 
	}
	
	/**
	 * 注册
	 * @return
	 */
	@RequestMapping("/register")
	public String register()
	{
		ConstatFinalUtil.LOGGER.info("--- register ---");
		return "/head/register"; 
	}
	

	/**
	 * 注册提交
	 * @return
	 */
	@RequestMapping("/registerSubmit")
	public String registerSubmit(HttpServletRequest request,AUsers users)
	{
		ConstatFinalUtil.LOGGER.info("--- registerSubmit ---");
		
		HttpSession session = request.getSession() ; 
		String rand = request.getParameter("rand");
		/* 验证码操作 */
		/* 从Session取出验证码图片的验证 */
		String randSess = session.getAttribute("rand") + "";
		
		/* 对比验证码 
		 * 万能验证码
		 * */
		if((randSess!= null && randSess.equalsIgnoreCase(rand)) || "0715".equalsIgnoreCase(rand))
		{
			/* 
			 * 驱动已经成功赋值了邮箱,密码
			 *  */
			/* 密码加密 */
			users.setPassword(EncryptUtil.encodeStr(users.getPassword()));
			users.setStatus(AUsersEnum.STATUS_ENABLE.getStatus());
			
			users.setCreateTime(new Date());
			users.setUpdateTime(new Date());
			users.setLastLoginTime(new Date());
			
			/* 入库 */
			JSONObject resultJSON = this.usersService.saveOneUsersService(users);
			/* 提示用户 */
			this.info = resultJSON.getString("info");
			if("0".equalsIgnoreCase(resultJSON.get("code")+""))
			{
				this.reSend(request,users.getEmail());	
			}			
		}else
		{
			this.info = ConstatFinalUtil.INFO_JSON.getString("7") ; 
		}
		request.setAttribute("info", info);
		return this.register(); 
	}
	/**
	 * 邮件重新发送
	 * @param users
	 */
	@RequestMapping("/reSend")
	public String reSend(HttpServletRequest request,String email)
	{
		// 根据email查询用户
		Map<String, Object>condMap = new HashMap<String,Object>();
		condMap.put("email", email);
		AUsers users = this.usersService.findOneUsersService(condMap);
		//生成连接
		Date sendEmailTime = new Date();
		String condUid = UUID.randomUUID().toString();
		String code = users.getEmail()+this.dateFormatUtil.format(sendEmailTime)+condUid;
		String verifyHref = ConstatFinalUtil.BUNDLE.getString("website.urlRootPath")+"/verifyEmail.htm?email="+users.getEmail()+"&code="+DigestUtils.sha256Hex(code);
		//储存用户扩展表
		AUsersExtend usersExtend = users.getUsersExtend();
		usersExtend.setEmailSendTime(sendEmailTime);
		usersExtend.setEmailSendCode(condUid);
		usersExtend.setUpdateTime(new Date());		
		//更新用户扩展表中的发送邮件相关的信息
		this.usersService.updateOneUsersService(users);
		//发邮件
		String fileName = "template/emailVerify.html";
		String subject = "欢迎使用用户中心(BJSXT)";
		Map<String, String>paramsMap = new HashMap<String,String>();
		paramsMap.put("subject", subject);
		paramsMap.put("email", users.getEmail());		
		paramsMap.put("verifyHref", verifyHref);
		paramsMap.put("date",this.dateFormatUtil.formatDate(new Date()));
		String result = this.fileUtil.replaceFile(fileName, paramsMap);
		this.springEmailUtil.sendMailHtml(users.getEmail(), subject, result);
		this.info += ",发送邮件成功,请到邮箱中去验证;<a href='"+ request.getContextPath() +"/reSend.htm?email="+ users.getEmail() +"'>重新发送</a>";
		return this.register();
	}
	/**
	 *验证邮箱的连接
	 */
	public String verifyEmail(HttpServletRequest request,String email)
	{
		//根据email查询用户
		Map<String, Object>condMap = new HashMap<String,Object>();
		condMap.put("email", email);
		AUsers users = this.usersService.findOneUsersService(condMap);
		if(users == null)
		{
			this.info="邮箱不存在";
		}else
		{
			AUsersExtend usersExtend = users.getUsersExtend();
			//检查过期时间
			long exp =1000*60*60*24;
			if(new Date().getTime()-usersExtend.getEmailSendTime().getTime()>exp)
			{
				//链接超时
				this.info ="链接超时";
				request.setAttribute("info", info);
				return "/head/info";
			}
			//验证链接的合法性
			String condUid = usersExtend.getEmailSendCode();
			String code = users.getEmail()+this.dateFormatUtil.format(usersExtend.getEmailSendTime())+condUid;
			code = DigestUtils.sha256Hex(code);
			String codeStr = request.getParameter("code");
			if(!code.equalsIgnoreCase(codeStr))
			{
				this.info = "链接非法";
				request.setAttribute("info", info);
				return "/head/info";
			}
			if(users.getEmailStatus() != AUsersEx)
			{
				
			}
		}
		return info;
		
	}
}